<script setup lang="ts">
import { searchConfig } from './config/search-config';
import { tableConfig } from './config/table-config';
import { generateNameToLevel } from '@/config/constant';
import { doGetBomMaterial } from '@/api/modeling/bom/index';
import { Message } from '@/instance';
import { isArray } from '@/utils';
import type { MaterialChooseVO } from '@/api/modeling/ProcessManagement/model/type';

defineProps(['visible', 'id']);
const emit = defineEmits(['update:visible', 'ok']);

let selectId: string;
let disabledList: MaterialChooseVO[] = [];
const dialogVisible = ref(false);
const tableRef = ref<TableRef>();
const disabledSelect = (row: MaterialChooseVO) =>
    !disabledList.some(item => row.id === item.materialId);

const { handleFullscreen, getMaxHeight } = useModal();

const selection = ref(false);
const isChildren = ref<boolean | null>(null);
const open = (data: MaterialChooseVO[] | string, child: boolean | null, isSelection?: boolean) => {
    dialogVisible.value = true;
    isChildren.value = child;
    selection.value = !!isSelection;
    if (isArray(data)) {
        disabledList = data as MaterialChooseVO[];
    } else {
        selectId = data as string;
    }
};

watch(
    () => tableRef.value?.tableData,
    (tableData: MaterialChooseVO[]) => {
        if (!selectId && !selection.value) return;
        if (tableData && Object.keys(tableData).length) {
            if (selection.value) {
                tableData.forEach(item => {
                    const hasIdItem = disabledList.some(
                        selectItem => item.id === selectItem.materialId
                    );
                    if (hasIdItem) tableRef.value!.toggleRowSelection(item, true); // 多选
                });
            } else {
                // 初始化物料编码列表选择行
                const row = tableData.filter((item: MaterialChooseVO) => item.id === selectId)[0]; // 单选
                if (row) tableRef.value?.setCurrentRow(row); // 设置表格选中当前行
            }
        }
    }
);

/**
 * 物料编码选择
 */
const handleOk = () => {
    const selectRow = selection.value ? materialList : tableRef.value?.selectTableRowData;

    dialogVisible.value = false;

    emit('ok', selectRow || {});
};

/**
 * 设置物料表格行样式名
 */
const getRowClassName = ({ row }: SlotData<MaterialChooseVO>) => {
    return !row.isUse ? '' : 'row-disabled';
};

/**
 * 点击当前物料列表行
 */
const handleRowClick = (row: MaterialChooseVO) => {
    if (selection.value) return;
    if (row.isUse) {
        Message.error('当前物料已被引用，请重新选择！');
        tableRef.value?.setCurrentRow();
        return;
    }
};

/**
 * 动态获取表格配置
 */
const getTableConfig = () => {
    tableConfig.unSelection = selection.value ? false : true;

    return tableConfig;
};

/**
 * 物料多选
 */
let materialList: MaterialChooseVO[] = [];
const handleSelection = (material: MaterialChooseVO[]) => {
    materialList = material;
};

const router = useRouter();
const toLink = () => {
    dialogVisible.value = false;
    router.push('/materialsManagement');
};

defineExpose({
    open
});
</script>

<template>
    <q-modal
        v-model:visible="dialogVisible"
        title="物料编码"
        width="865px"
        ok-text="保存"
        :fullscreen="true"
        :centered="true"
        @ok="handleOk"
        @fullscreen="handleFullscreen"
    >
        <base-search
            ref="searchRef"
            :table-ref="tableRef"
            :search-config="searchConfig"
            :close-min-width="true"
        >
            <q-push-button :is-text="false" @click="toLink" />
        </base-search>

        <base-table
            :id="generateNameToLevel('3')"
            ref="tableRef"
            :max-height="getMaxHeight"
            :tableConfig="getTableConfig()"
            :getDataFn="params => doGetBomMaterial({ ...params })"
            :table-attr="{ rowClassName: getRowClassName }"
            :modal-mode="true"
            :show-setting="false"
            :un-action="true"
            :added-params="{ isChildren }"
            :selectable="disabledSelect"
            @selection-change="handleSelection"
            @row-click="handleRowClick"
        >
        </base-table>
    </q-modal>
</template>

<style scoped lang="scss">
:deep() {
    @include disabled-tooltip();
}

@include b(m-select) {
    @include e(material) {
        @include flex(flex-start);

        margin-bottom: 8px;
        font-size: 14px;
        color: var(--q-text-color-primary);

        label {
            display: block;
        }
    }
}

:deep() {
    .row-disabled {
        cursor: not-allowed;
    }
}
</style>
./config/table-config
